"""
RGB通道编辑器对话框
"""

import tkinter as tk
from tkinter import ttk, messagebox
from PIL import Image, ImageTk
import numpy as np
from typing import Optional, Callable

from ...utils import get_logger
from .channel_control_panel import ChannelControlPanel


class ChannelEditorDialog:
    """RGB通道编辑器对话框"""
    
    def __init__(
        self,
        parent: tk.Tk,
        image: np.ndarray,
        on_apply: Optional[Callable] = None
    ):
        """
        初始化通道编辑器
        
        Args:
            parent: 父窗口
            image: 原始图片 (RGB)
            on_apply: 应用回调函数 (channel_image: np.ndarray, channel_config: dict)
        """
        self.parent = parent
        self.image = image
        self.on_apply = on_apply
        self.logger = get_logger(__name__)
        
        # 创建窗口
        self.window = tk.Toplevel(parent)
        self.window.title("RGB通道编辑器")
        self.window.geometry("1000x700")
        self.window.transient(parent)
        self.window.grab_set()
        
        # 初始化控制面板
        self.control_panel = None
        
        # 创建UI
        self._create_ui()
        
        # 初始预览
        self._update_preview()
    
    def _create_ui(self):
        """创建用户界面"""
        # 顶部说明
        self._create_header()
        
        # 主容器
        main_container = ttk.Frame(self.window)
        main_container.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        # 左侧：控制面板
        control_frame = ttk.LabelFrame(main_container, text="通道控制", padding=10)
        control_frame.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 5))
        
        # 创建控制面板
        self.control_panel = ChannelControlPanel(
            control_frame,
            self.image,
            self._update_preview
        )
        
        # 右侧：预览区域
        self._create_preview_area(main_container)
        
        # 底部按钮
        self._create_bottom_buttons()
    
    def _create_header(self):
        """创建顶部说明"""
        info_frame = ttk.Frame(self.window, padding=10)
        info_frame.pack(fill=tk.X)
        
        ttk.Label(
            info_frame,
            text="📊 RGB通道编辑器",
            font=("Arial", 14, "bold")
        ).pack(side=tk.LEFT)
        
        ttk.Label(
            info_frame,
            text="通道图用于SAM输入识别mask，最终裁剪使用原图",
            font=("Arial", 10),
            foreground="gray"
        ).pack(side=tk.LEFT, padx=20)
    
    def _create_preview_area(self, parent):
        """创建预览区域"""
        preview_frame = ttk.LabelFrame(parent, text="预览", padding=10)
        preview_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        # 预览画布
        self.preview_canvas = tk.Canvas(
            preview_frame,
            bg="#2b2b2b",
            highlightthickness=1,
            highlightbackground="gray"
        )
        self.preview_canvas.pack(fill=tk.BOTH, expand=True)
        
        # 预览信息
        self.preview_info_label = ttk.Label(
            preview_frame,
            text="",
            font=("Arial", 9),
            foreground="gray"
        )
        self.preview_info_label.pack(pady=5)
    
    def _create_bottom_buttons(self):
        """创建底部按钮"""
        button_frame = ttk.Frame(self.window, padding=10)
        button_frame.pack(fill=tk.X)
        
        # 提示信息
        ttk.Label(
            button_frame,
            text="💡 将通道图作为SAM输入，分割后用mask裁剪原图（支持撤销）",
            foreground="#0066cc",
            font=("Arial", 9, "italic")
        ).pack(side=tk.LEFT, padx=10)
        
        # 按钮
        ttk.Button(
            button_frame,
            text="取消",
            command=self.window.destroy,
            width=12
        ).pack(side=tk.RIGHT, padx=5)
        
        ttk.Button(
            button_frame,
            text="应用通道图",
            command=self._on_apply_click,
            bootstyle="success",
            width=15
        ).pack(side=tk.RIGHT, padx=5)
    
    def _update_preview(self):
        """更新预览"""
        try:
            # 获取预览图像
            preview = self.control_panel.get_preview_image()
            
            # 显示预览
            self._display_preview(preview)
            
            # 更新信息
            info = self.control_panel.get_info_text()
            self.preview_info_label.config(text=info)
            
        except Exception as e:
            self.logger.error(f"更新预览失败: {e}", exc_info=True)
    
    def _display_preview(self, preview_image: np.ndarray):
        """显示预览图像"""
        # 清空画布
        self.preview_canvas.delete("all")
        
        # 获取画布尺寸
        self.preview_canvas.update()
        canvas_width = self.preview_canvas.winfo_width()
        canvas_height = self.preview_canvas.winfo_height()
        
        if canvas_width <= 1 or canvas_height <= 1:
            canvas_width = 600
            canvas_height = 500
        
        # 调整图片大小
        h, w = preview_image.shape[:2]
        scale = min(canvas_width / w, canvas_height / h) * 0.95
        new_w = int(w * scale)
        new_h = int(h * scale)
        
        import cv2
        resized = cv2.resize(preview_image, (new_w, new_h))
        
        # 转换为PIL图像
        pil_image = Image.fromarray(resized)
        photo = ImageTk.PhotoImage(pil_image)
        
        # 居中显示
        x = (canvas_width - new_w) // 2
        y = (canvas_height - new_h) // 2
        
        self.preview_canvas.create_image(x, y, anchor=tk.NW, image=photo)
        self.preview_canvas.image = photo
    
    def _on_apply_click(self):
        """应用按钮回调"""
        # 检查至少启用一个通道
        if not self.control_panel.is_valid():
            messagebox.showwarning("警告", "请至少启用一个通道！", parent=self.window)
            return
        
        # 生成处理后的图像
        channel_image = self.control_panel.generate_combined_image()
        
        # 获取配置信息
        channel_config = self.control_panel.get_channel_config()
        
        self.logger.info(f"应用通道配置: {channel_config}")
        
        # 调用回调
        if self.on_apply:
            self.on_apply(channel_image, channel_config)
        
        # 关闭窗口
        self.window.destroy()

